package com.rcloud.server.sealtalk.util;

import com.rcloud.server.sealtalk.configuration.SealtalkConfig;
import com.rcloud.server.sealtalk.model.response.APIResultWrap;
import com.rcloud.server.sealtalk.service.AttachFileService;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

/**
 * @author xiaochaoge
 * @title: ProductpPcturesDealUtil
 * @projectName sealtalk-server
 * @description: TODO
 * @date 2022-06-3016:35:57
 */
@Slf4j
@Component
public class ImageHandleUtils {

    @Autowired
    private AttachFileService attachFileService;

    @Resource
    private SealtalkConfig sealtalkConfig;

    public static void main(String[] args) throws Exception {
//        String imageUri = "https://img.lingtingkj.com/FiLzEpA0QoRcHNXFbLEf6_q7fBzA";
//        String imageEncodeBase64 = ImageHandleUtils.getImageEncodeBase64(imageUri,960);
//        MultipartFile multipartFile = BASE64DecodedMultipartFile.base64ToMultipart(imageEncodeBase64);
//        System.out.println("图片名称信息:"+ multipartFile.getOriginalFilename());
//        BufferedImage imageInfo = getImageInfo(imageEncodeBase64);
//        System.out.println(imageInfo.getHeight());
//        System.out.println(imageInfo.getWidth());
//
//        double len = imageEncodeBase64.length()/1024;
//        System.out.println("图片base64大小(kb)："+String.valueOf(len));
//        //base64图片大小：将base64数据的长度乘以3/4，因为编码将6个字节变为8个字节。如果结果在4MB的几个字节内，那么您需要计算末尾的=数
//        System.out.println("图片大小(kb)："+len*0.75);
    }

    public String getImageEncodeBase64(String imageUri,Integer size) throws IOException {
        if (imageUri.contains("http://")) {
            imageUri = imageUri.replace("http://", "https://");
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        URL url = new URL(imageUri);
        // 图片对象
        BufferedImage bufferedImage = ImageIO.read(url.openStream());
        // 宽度
        int width = bufferedImage.getWidth();
        // 高度
        int height = bufferedImage.getHeight();

        log.info("图片信息打印width:" + width);
        log.info("图片信息打印height:" + height);

        if (width > size && height > size) {
            //将原图按比例缩放，最宽240，最高240，不进行质量压缩
            Thumbnails.of(bufferedImage).width(size).height(size).outputQuality(0.7).outputFormat("jpg").toOutputStream(out);
        } else if (width > size && height < size) {
            //将原图按比例缩放，最宽300，最高400，不进行质量压缩
            Thumbnails.of(bufferedImage).width(size).outputQuality(0.7).outputFormat("jpg").toOutputStream(out);

        } else if (width < size && height > size) {
            //将原图按比例缩放，最宽300，最高400，不进行质量压缩
            Thumbnails.of(bufferedImage).height(size).outputQuality(0.7).outputFormat("jpg").toOutputStream(out);

        } else {
            //将原图按比例缩放，最宽300，最高400，不进行质量压缩
            Thumbnails.of(bufferedImage).outputQuality(1).outputFormat("jpg").toOutputStream(out);
        }
        return ImageHandleUtils.imageThumbnailsToBase64(out);
    }

    public static String getImageEncodeBase64(String imageUri) throws IOException {
        if (imageUri.contains("http://")) {
            imageUri = imageUri.replace("http://", "https://");
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        URL url = new URL(imageUri);
        // 图片对象
        BufferedImage bufferedImage = ImageIO.read(url.openStream());
        // 宽度
        int width = bufferedImage.getWidth();
        // 高度
        int height = bufferedImage.getHeight();
        log.info("图片信息打印width:" + width);
        log.info("图片信息打印height:" + height);
        return ImageHandleUtils.imageThumbnailsToBase64(out);
    }

    //转换
    public static String imageThumbnailsToBase64(ByteArrayOutputStream bs) {
        String back = "true";
        try {
            // 图片转换为base64并返回
            BASE64Encoder encoder = new sun.misc.BASE64Encoder();
            byte[] bytes = bs.toByteArray();
            return encoder.encodeBuffer(bytes).trim();
        } catch (Exception e) {
            back = "false";
            System.out.println("Thumbnails Upload failed：" + e);
        }
        return back;
    }

    public static BufferedImage getImageInfo(String chart) throws IOException {
        if (StringUtils.isNotEmpty(chart)) {
            byte[] decoder = new BASE64Decoder().decodeBuffer(chart);
            InputStream is = new ByteArrayInputStream(decoder);
            return ImageIO.read(is);
        }
        return null;
    }

    /**
     * 图片上传
     */
    public String uploadFile(String imageUri) throws IOException {
        String imageEncodeBase64 = getImageEncodeBase64(imageUri, 960);
        MultipartFile multipartFile = BASE64DecodedMultipartFile.base64ToMultipart(imageEncodeBase64);
        String fileName = attachFileService.uploadFile(multipartFile.getBytes(), multipartFile.getOriginalFilename());
        log.info("图片名称信息:{}",multipartFile.getOriginalFilename());
        String imageUrl = "https://" + sealtalkConfig.getQiniuBucketDomain() + "/" + fileName;
        log.info("图片imageUrl:{}",imageUrl);
        return imageUrl;
    }


}
